package cn.thinkjoy.LawDataForExcel.email;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.*;
import java.util.Date;
import java.util.Properties;
import javax.mail.internet.MimeMessage.RecipientType;

public class MailUtils {
    /**
     * 发送邮件
     * @throws Exception 
     * 
     */
    public static void sendMsg(String fromAddress,String fromAddresspwd,String host,
                               String toAddress,String subject,String content,String filepath) throws Exception{
        // 用于连接邮件服务器的参数配置
        Properties props = new Properties();
        //发送邮件的服务器地址
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.auth", "true");
        props.put("mail.transport.protocol","smtp");
        props.put("mail.debug", "true");
        //创建Session对象
        Session session =Session.getInstance(props);
        //创建出MimeMessage，邮件的消息对象
        MimeMessage message = new MimeMessage(session);
        //设置发件人
        Address fromAddr = new InternetAddress(fromAddress,"每日执法信息导出小助手");
        message.setFrom(fromAddr);

        //设置收件人
        Address toAddr=new InternetAddress(toAddress,"无敌小神童");
        message.setRecipient(RecipientType.TO, toAddr);

        //设置邮件的主题
        message.setSubject(subject,"UTF-8");

        //设置文本节点
        MimeBodyPart text=new MimeBodyPart();
        text.setContent(content,"text/html;charset=UTF-8");

        //创建附件节点
        MimeBodyPart attachment=new MimeBodyPart();
        DataHandler dataHandler=new DataHandler(new FileDataSource(filepath));// 读取本地文件
        attachment.setDataHandler(dataHandler);// 将附件数据添加到“节点”
        attachment.setFileName(MimeUtility.encodeText(dataHandler.getName()));// 设置附件的文件名（需要编码）

        //设置文本和图片的关系
        MimeMultipart mimeMultipart=new MimeMultipart();
        mimeMultipart.addBodyPart(text);
        mimeMultipart.addBodyPart(attachment);
        mimeMultipart.setSubType("mixed");

        //设置邮件的正文
        message.setContent(mimeMultipart);
        //用于连接邮件服务器的参数配置
        message.setSentDate(new Date());
        message.saveChanges();//保存更新

        //根据 Session 获取邮件传输对象
        Transport transport = session.getTransport("smtp");
        transport.connect(host,fromAddress,fromAddresspwd); //设置了邮件的发射地址
        //发送邮件到收件地址
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();
    }
}